package com.pingan.haofang.searchcloud.api.query.parser.dbobject.sqlnode.aggregate;

import org.apache.commons.lang3.StringUtils;

import com.pingan.haofang.searchcloud.api.query.parser.dbobject.FunctionConfig;
import com.pingan.haofang.searchcloud.api.query.parser.dbobject.SqlNode;
import com.pingan.haofang.searchcloud.api.query.parser.dbobject.sqlnode.ColumnNode;
import com.pingan.haofang.searchcloud.api.query.parser.dbobject.util.SqlNodeUtil;

/**
 * ClassName: Count <br>
 * Function:
 *
 * @author luyi
 * @version 1.0.0
 * @since 1.0.0
 * @date 20150816
 */
public class Count extends AggregateFunction {

    private static final int VALUE_PARAM_COUNT = 2;

    private boolean wildcard;

    public Count() {
        setName(FunctionConfig.COUNT.name);
    }

    @Override
    public Object getValue(Object...params) {
        assertParamCount(params, VALUE_PARAM_COUNT);
        assertParamType(params, Number.class);
        return Long.parseLong(params[0].toString()) + Long.parseLong(params[1].toString());
    }

    @Override
    public int getParamCount() {
        return 1;
    }

    public boolean isWildcard() {
        return wildcard;
    }

    public void setWildcard(boolean wildcard) {
        this.wildcard = wildcard;
    }

    public String getFullName() {
        StringBuilder sb = new StringBuilder();
        sb.append(name).append("(");
        if (wildcard) {
            sb.append("*");
        } else if (params != null) {
            for (SqlNode param : params) {
                if (SqlNodeUtil.isColumn(param)) {
                    ColumnNode columnNode = (ColumnNode) param;
                    if (StringUtils.isNotBlank(columnNode.getSchema())) {
                        sb.append(columnNode.getSchema()).append(".");
                    }
                    sb.append(columnNode.getColumnName());
                } else {
                    sb.append(param.toString());
                }
            }
        }
        sb.append(")");
        return sb.toString();
    }
}
